package com.software.loginregister.activity;

import androidx.appcompat.app.AppCompatActivity;

import android.app.ProgressDialog;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.software.loginregister.R;
import com.software.loginregister.entity.EVResponse;
import com.software.loginregister.entity.ResetPasswordRequest;
import com.software.loginregister.util.RetrofitClient;

import java.io.IOException;

import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;


public class ForgetPasswordActivity extends AppCompatActivity {
    private EditText etEmail;
    private EditText etVerificationCode;
    private EditText etNewPassword;
    private EditText etConfirmPassword;
    private Button btnSendCode;
    private Button btnResetPassword;
    private static final String TAG = "ForgetPasswordActivity";
    private TextView tvCodeTimer;
    private boolean isVerifying = false; // 添加标志位
    private CountDownTimer verificationCodeTimer; // 添加计时器引用

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_forget_password);

        initViews();
        setupListeners();
    }

    private void initViews() {
        etEmail = findViewById(R.id.edt_forgot_email);
        etVerificationCode = findViewById(R.id.edt_verification_code);
        etNewPassword = findViewById(R.id.edt_new_password);
        etConfirmPassword = findViewById(R.id.edt_confirm_password);
        btnSendCode = findViewById(R.id.btn_send_code);
        btnResetPassword = findViewById(R.id.btn_reset_password);
    }

    private void setupListeners() {
        btnSendCode.setOnClickListener(v -> sendVerificationCode());
        btnResetPassword.setOnClickListener(v -> resetPassword());
    }


    private void sendVerificationCode() {
        String email = etEmail.getText().toString().trim();
        if (email.isEmpty()) {
            Log.w(TAG, "Email is empty");
            Toast.makeText(this, "请输入邮箱", Toast.LENGTH_SHORT).show();
            return;
        }

        // 添加邮箱格式验证
        if (!android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches()) {
            Log.w(TAG, "Invalid email format: " + email);
            Toast.makeText(this, "请输入有效的邮箱地址", Toast.LENGTH_SHORT).show();
            return;
        }

        Log.d(TAG, "Sending verification code to email: " + email);

        // 显示加载对话框
        ProgressDialog progressDialog = new ProgressDialog(this);
        progressDialog.setMessage("发送验证码中...");
        progressDialog.show();


        RetrofitClient.getInstance().getUserApi()
                .sendVerificationCode(email)
                .enqueue(new Callback<ResponseBody>() { // 改用 ResponseBody 而不是 ApiResponse
                    @Override
                    public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                        progressDialog.dismiss();
                        Log.d(TAG, "Response received - Code: " + response.code());
                        Log.d(TAG, "Request URL: " + call.request().url());

                        try {
                            if (response.isSuccessful()) {
                                String responseString = response.body().string();
                                Log.d(TAG, "Raw response: " + responseString);

                                // 假设服务器返回成功时的响应是简单的文本消息
                                if (response.code() == 200) {
                                    Log.i(TAG, "Verification code sent successfully");
                                    Toast.makeText(ForgetPasswordActivity.this,
                                            "验证码已发送，请查收邮件", Toast.LENGTH_SHORT).show();
                                    disableSendButton();
                                    startVerificationCodeTimer();
                                } else {
                                    Log.e(TAG, "Failed to send code: " + responseString);
                                    Toast.makeText(ForgetPasswordActivity.this,
                                            responseString, Toast.LENGTH_SHORT).show();
                                }
                            } else {
                                String errorBody = response.errorBody() != null ?
                                        response.errorBody().string() : "未知错误";
                                Log.e(TAG, "Error response: " + errorBody);
                                Toast.makeText(ForgetPasswordActivity.this,
                                        "发送失败: " + errorBody, Toast.LENGTH_SHORT).show();
                            }
                        } catch (IOException e) {
                            Log.e(TAG, "Error reading response", e);
                            Toast.makeText(ForgetPasswordActivity.this,
                                    "发送失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onFailure(Call<ResponseBody> call, Throwable t) {
                        progressDialog.dismiss();
                        Log.e(TAG, "Network call failed", t);
                        Log.e(TAG, "Failed URL: " + call.request().url());

                        String errorMessage;
                        if (t instanceof java.net.SocketTimeoutException) {
                            errorMessage = "连接超时，请检查网络后重试";
                        } else if (t instanceof java.net.UnknownHostException) {
                            errorMessage = "无法连接到服务器，请检查网络设置";
                        } else {
                            errorMessage = "发送失败: " + t.getMessage();
                        }

                        Log.e(TAG, errorMessage, t);
                        Toast.makeText(ForgetPasswordActivity.this,
                                errorMessage, Toast.LENGTH_SHORT).show();
                    }
                });
    }

    // 禁用发送按钮60秒
    private void disableSendButton() {
        btnSendCode.setEnabled(false);
        new CountDownTimer(60000, 1000) {
            public void onTick(long millisUntilFinished) {
                btnSendCode.setText(millisUntilFinished / 1000 + "秒后重试");
            }

            public void onFinish() {
                btnSendCode.setEnabled(true);
                btnSendCode.setText("发送验证码");
            }
        }.start();
    }

    private void resetPassword() {
        if (isVerifying) {
            Log.d(TAG, "Already processing verification");
            return; // 如果正在验证中，直接返回
        }

        String email = etEmail.getText().toString().trim();
        String code = etVerificationCode.getText().toString().trim();
        String newPassword = etNewPassword.getText().toString().trim();
        String confirmPassword = etConfirmPassword.getText().toString().trim();

        // 输入验证
        if (email.isEmpty() || code.isEmpty() || newPassword.isEmpty() || confirmPassword.isEmpty()) {
            Log.w(TAG, "Some fields are empty");
            Toast.makeText(this, "请填写完整信息", Toast.LENGTH_SHORT).show();
            return;
        }

        if (!android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches()) {
            Toast.makeText(this, "请输入有效的邮箱地址", Toast.LENGTH_SHORT).show();
            return;
        }

        if (code.length() != 6) {  // 假设验证码是6位
            Toast.makeText(this, "请输入正确的验证码", Toast.LENGTH_SHORT).show();
            return;
        }

        if (newPassword.length() < 6) {  // 密码最少6位
            Toast.makeText(this, "密码长度不能少于6位", Toast.LENGTH_SHORT).show();
            return;
        }

        if (!newPassword.equals(confirmPassword)) {
            Log.w(TAG, "Passwords do not match");
            Toast.makeText(this, "两次输入的密码不一致", Toast.LENGTH_SHORT).show();
            return;
        }
        isVerifying = true; // 设置标志位
        btnResetPassword.setEnabled(false); // 禁用重置按钮

        // 显示加载对话框
        ProgressDialog progressDialog = new ProgressDialog(this);
        progressDialog.setMessage("正在重置密码...");
        progressDialog.show();

        // 直接进行密码重置，不再单独验证验证码
        ResetPasswordRequest request = new ResetPasswordRequest(email, code, newPassword);
        Log.d(TAG, "Sending reset password request - Email: " + email + ", Code: " + code);

        RetrofitClient.getInstance().getUserApi()
                .resetPassword(request)
                .enqueue(new Callback<EVResponse>() {
                    @Override
                    public void onResponse(Call<EVResponse> call, Response<EVResponse> response) {
                        try {
                            if (response.isSuccessful() && response.body() != null) {
                                EVResponse apiResponse = response.body();
                                Log.d(TAG, "Password reset response - Success: " + apiResponse.isSuccess()
                                        + ", Message: " + apiResponse.getMessage());

                                if (apiResponse.isSuccess()) {
                                    Toast.makeText(ForgetPasswordActivity.this,
                                            "密码重置成功", Toast.LENGTH_SHORT).show();
                                    finish();
                                } else {
                                    Toast.makeText(ForgetPasswordActivity.this,
                                            apiResponse.getMessage(), Toast.LENGTH_SHORT).show();
                                }
                            } else {
                                String errorBody = response.errorBody() != null ?
                                        response.errorBody().string() : "未知错误";
                                Toast.makeText(ForgetPasswordActivity.this,
                                        "重置密码失败: " + errorBody, Toast.LENGTH_SHORT).show();
                            }
                        } catch (Exception e) {
                            Log.e(TAG, "Error processing response", e);
                            Toast.makeText(ForgetPasswordActivity.this,
                                    "处理响应时出错", Toast.LENGTH_SHORT).show();
                        } finally {
                            progressDialog.dismiss();
                            isVerifying = false;
                            btnResetPassword.setEnabled(true);
                        }
                    }

                    @Override
                    public void onFailure(Call<EVResponse> call, Throwable t) {
                        Log.e(TAG, "Network call failed", t);
                        progressDialog.dismiss();
                        isVerifying = false;
                        btnResetPassword.setEnabled(true);
                        Toast.makeText(ForgetPasswordActivity.this,
                                "网络错误，请重试", Toast.LENGTH_SHORT).show();
                    }
                });
    }
    private void startVerificationCodeTimer() {
        tvCodeTimer = findViewById(R.id.tvCodeTimer);
        tvCodeTimer.setVisibility(View.VISIBLE);

        if (verificationCodeTimer != null) {
            verificationCodeTimer.cancel();
        }

        verificationCodeTimer = new CountDownTimer(15 * 60 * 1000, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                long minutes = millisUntilFinished / (60 * 1000);
                long seconds = (millisUntilFinished % (60 * 1000)) / 1000;
                tvCodeTimer.setText(String.format("验证码有效期剩余: %02d:%02d", minutes, seconds));
            }

            @Override
            public void onFinish() {
                tvCodeTimer.setText("验证码已过期，请重新获取");
            }
        }.start();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (verificationCodeTimer != null) {
            verificationCodeTimer.cancel();
        }
    }
}